<template>
    <el-row>
        <el-col :span="24">
            <div class="grid-content bg-purple-dark">
                <h4 style="line-height:36px;">商品管理</h4>
            </div>
        </el-col>
        <el-col :span="24">
            <div class="padding-content">
                <div style="display: flex;justify-content: flex-end;margin-bottom:20px;">
                    <el-button type="primary" size="small" @click="openAdd">添加</el-button>
                </div>
                <div class="table">
                    <el-table :data="goodsInfo" border style="width: 100%">
                        <!-- <el-table-column
                            prop="id"
                            label="商品id">
                        </el-table-column> -->
                        <el-table-column prop="name" label="商品名称">
                        </el-table-column>
                        <el-table-column label="分类">
                            <template slot-scope="scope">
                                {{getType(scope.row.category_id)}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="spec" label="规格">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="specShow(scope.row)">查看</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="unit" label="单位">
                        </el-table-column>
                        <!-- <el-table-column prop="real_price" label="价格">
                        </el-table-column>
                        <el-table-column prop="stock" label="库存">
                        </el-table-column> -->
                        <!-- <el-table-column
                            label="轮播图片">
                            <template slot-scope="scope" >
                                <el-button type="text" size="small" @click="editInfo(scope.row,'img')">编辑</el-button>
                                <img :src="scope.row.imgs[0]" class="mainImg" />
                                <img :src="item" v-for="(item,index) in scope.row.imgs" :key="index" class="mainImg"/>
                            </template>
                        </el-table-column> -->
                        <el-table-column label="详情">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="editInfo(scope.row)">编辑</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" style="color:red" @click="deleteGoods(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <el-pagination layout="prev, pager, next" :total="total" :page-size="page_size" @current-change="handleCurrentChange">
            </el-pagination>
        </el-col>
        <el-dialog :visible.sync="specVisible" title="规格详情">
            <el-table :data="specShowList" border style="width: 100%">
                <el-table-column prop="name" label="规格名称">
                </el-table-column>
                <el-table-column prop="stock" label="库存">
                </el-table-column>
                <el-table-column prop="real_price" label="售价">
                </el-table-column>
                <el-table-column prop="price" label="划线价格">
                </el-table-column>
            </el-table>
        </el-dialog>
        <el-dialog :visible.sync="addVisible" title="添加商品" :before-close="addHandleClose">
            <div class="form-content">
                <div class="row">
                    <div class="item">
                        <label>商品分类:</label>
                        <el-select v-model="category_id" placeholder="请选择">
                            <el-option v-for="item in category" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                </div>
                <div class="item">
                    <label>商品名称:</label>
                    <el-input v-model="add_name" placeholder="请输入名称" maxlength="40"></el-input>
                </div>
                <div style="border: 1px solid #f8f8f8; padding: 1rem; margin-bottom: 1rem;">
                    <div class="row" style="position: relative;">
                        <div class="item">
                            <label><span style="font-size: 1.2rem">规格管理</span></label>
                        </div>
                        <el-button style=" position: absolute;right: 2rem;top: -10px;" type="primary" @click="addSpec">添加</el-button>
                    </div>
                    <div class="row">
                        <div class="item">
                            <label>规格名称:</label>
                            <el-input v-model="specItem.name" placeholder="请输入规格名称"></el-input>
                        </div>
                        <div class="item">
                            <label>商品库存:</label>
                            <el-input v-model="specItem.stock" placeholder="请输入库存量"></el-input>
                        </div>
                    </div>
                    <div class="row">
                        <div class="item">
                            <label>零售价格:</label>
                            <el-input v-model="specItem.real_price" placeholder="请输入售价"></el-input>
                        </div>
                        <div class="item">
                            <label>划线价格:</label>
                            <el-input v-model="specItem.price" placeholder="请输入划线价"></el-input>
                        </div>
                    </div>
                    <div class="row" style="margin-top: 1rem;" v-for="(item, index) in specList">
                        <div class="spec_item">
                            规格名称:<span>{{item.name}}</span> ；商品库存：<span>{{item.stock}}</span>；零售价格：<span>{{item.real_price}}元</span>；划线价格：<span>{{item.price}}</span>元；
                        </div>
                        <el-button size="small" type="danger" style="margin-left: 10px;" @click="delSpec(index)">删除</el-button>
                    </div>
                </div>
                <div class="row">
                    <div class="item">
                        <label>商品单位:</label>
                        <el-select v-model="unit" placeholder="请选择">
                            <el-option v-for="item in unitList" :key="item.value" :label="item.name" :value="item.value">
                            </el-option>
                        </el-select>
                        <!-- <el-input v-model="unit" placeholder="请输入单位"></el-input> -->
                    </div>
                </div>
                <div class="row">
                    <div class="item" style="width:100%;">
                        <label style="width:15%;">商品主图片:</label>
                        <upload ref="upload" :uploadImgList="img_urls"></upload>
                    </div>
                </div>
                <div class="row">
                    <label>详情:</label>
                    <div class="editor_content">
                        <edit @catchData="catchData" :initial="edit.detail"></edit>
                    </div>
                </div>
            </div>
            <div style="display:flex;justify-content:center;margin-top:20px;">
                <el-button type="primary" @click="submitGoods" :disabled="no">添加</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="EditVisible" title="编辑图片" :before-close="editHandleClose">
            <div class="form-content">
                <div class="item">
                    <label>商品分类:</label>
                    <el-select v-model="edit.category_id" placeholder="请选择">
                        <el-option v-for="item in category" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div class="item">
                    <label for="name">商品名称:</label>
                    <el-input v-model="edit.name" placeholder="请输入名称" maxlength="40"></el-input>
                </div>
                <div style="border: 1px solid #f8f8f8; padding: 1rem; margin-bottom: 1rem;">
                    <div class="row" style="position: relative;">
                        <div class="item">
                            <label><span style="font-size: 1.2rem">规格管理</span></label>
                            <!-- <el-input v-model="guige" placeholder="请输入规格"></el-input> -->
                        </div>
                        <el-button style=" position: absolute;right: 2rem;top: -10px;" type="primary" @click="addSpec">添加</el-button>
                    </div>

                    <div class="row">
                        <div class="item">
                            <label>规格名称:</label>
                            <el-input v-model="specItem.name" placeholder="请输入规格名称"></el-input>
                        </div>
                        <div class="item">
                            <label>商品库存:</label>
                            <el-input v-model="specItem.stock" placeholder="请输入库存量"></el-input>
                        </div>
                    </div>
                    <div class="row">
                        <div class="item">
                            <label>零售价格:</label>
                            <el-input v-model="specItem.real_price" placeholder="请输入售价"></el-input>
                        </div>
                        <div class="item">
                            <label>划线价格:</label>
                            <el-input v-model="specItem.price" placeholder="请输入划线价"></el-input>
                        </div>
                    </div>
                    <div class="row" style="margin-top: 1rem;" v-for="(item, index) in specList">
                        <div class="spec_item">
                            规格名称:<span>{{item.name}}</span> ；商品库存：<span>{{item.stock}}</span>；零售价格：<span>{{item.real_price}}元</span>；划线价格：<span>{{item.price}}</span>元；
                        </div>
                        <el-button size="small" type="danger" style="margin-left: 10px;" @click="delSpec(index)">删除</el-button>
                    </div>
                </div>
                <div class="row">
                    <div class="item">
                        <label>商品单位:</label>
                        <el-select v-model="edit.unit" placeholder="请选择">
                            <el-option v-for="item in unitList" :key="item.value" :label="item.name" :value="item.value">
                            </el-option>
                        </el-select>
                        <!-- <el-input v-model="edit.unit" placeholder="请输入单位"></el-input> -->
                    </div>
                </div>
                <div class="item">
                    <label>商品主图片:</label>
                    <upload ref="upload" :uploadImgList="img_urls"></upload>
                </div>
                <div class="item">
                    <label>详情:</label>
                    <div class="editor_content">
                        <edit @catchData="catchData" :initial="edit.detail"></edit>
                    </div>
                </div>
            </div>
            <div style="display:flex;justify-content:center;margin-top:20px;">
                <el-button type="primary" @click="submitEdit">确定</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>
<script>
import axios from "axios";
import upload from "../../components/upload";
import edit from "../../components/edit";
import category from "../../tool/category_id";
export default {
  data() {
    return {
      mainImage: [], //主图片
      detailImage: [], //详情图片
      addVisible: false,
      EditVisible: false,
      // mainImgVisible:false,
      goodsInfo: [],
      category_id: "",
      unit: "",
      price: "", //划线价
      details: "",
      stock: "", //库存
      real_price: "", //售价
      img_urls: [],
      category: category,
      page: 1,
      page_size: 10,
      edit:{},
      editImgs: [],
      add_name: "",
      guige: "",
      total: 0,
      addSpecArr: [],
      specList: [],
      specShowList: [],
      specItem: {
        //新增规格类
        name: "",
        stock: "",
        price: "",
        real_price: ""
      },
      specVisible: false,
      unitList: [
        {
          name: "袋",
          value: "袋"
        },
        {
          name: "罐",
          value: "罐"
        },
        {
          name: "只",
          value: "只"
        },
        {
          name: "条",
          value: "条"
        },
        {
          name: "套",
          value: "套"
        },
        {
          name: "个",
          value: "个"
        },
        {
          name: "片",
          value: "片"
        },
        {
          name: "支",
          value: "支"
        },
        {
          name: "颗",
          value: "颗"
        },
        {
          name: "台",
          value: "台"
        },
        {
          name: "盒",
          value: "盒"
        },
        {
          name: "桶",
          value: "桶"
        },
        {
          name: "包",
          value: "包"
        },
        {
          name: "辆",
          value: "辆"
        },
        {
          name: "根",
          value: "根"
        },
        {
          name: "件",
          value: "件"
        }
      ]
    };
  },
  components: {
    upload,
    edit
  },
  computed: {
    good_name() {
      return this.name + "-" + this.guige;
    },
    no() {
      if (
        !this.category_id ||
        !this.add_name ||
        !this.unit ||
        !this.details ||
        this.specList.length == 0
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  // watch: {
  //   specItem: {
  //     handler(newVal, oldVal) {
  //       if (
  //         newVal.price &&
  //         newVal.real_price &&
  //         newVal.price * 1 < newVal.real_price * 1
  //       ) {
  //         this.$message({
  //           message: `售价不能大于划线价格`,
  //           type: "error"
  //         });
  //       }
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  methods: {
    // 打开添加时清空数据
    openAdd() {
      this.addVisible = true;
      this.specList = [];
      this.unit = "";
      this.img_urls = [];
      this.edit.detail = "";
      this.specItem = {
        name: "",
        stock: "",
        price: "",
        real_price: ""
      };
    },
    // 添加规格
    addSpec() {
      let { name, stock, price, real_price } = this.specItem;
      console.log(real_price*1 > price*1)
      if (name && stock && price && real_price) {
        if (real_price*1 > price*1) {
          this.$message({
            message: `售价不能大于划线价格`,
            type: "error"
          });
          return;
        }
      } else {
        this.$message({
          message: `请完善规格内容`,
          type: "error"
        });
        return;
      }
      this.specList.push(this.specItem);
      this.specItem = {
        name: "",
        stock: "",
        price: "",
        real_price: ""
      };
    },
    // 删除规格
    delSpec(index) {
      this.specList.splice(index, 1);
    },
    specShow(item) {
      this.specShowList = item.specs;
      this.specVisible = true;
    },
    getType(value) {
      for (let i of category) {
        if (value == i.value) {
          return i.label;
        }
      }
    },
    editHandleClose() {
      this.EditVisible = false;
      // this.edit.detail = "关闭编辑";
    },
    addHandleClose() {
      // this.edit.detail = ""
      // this.edit.detail = "关闭编辑";
      this.addVisible = false;
    },
    // 获取富文本框的内容
    catchData(value) {
      console.log(value);
      this.details = value; //在这里接受子组件传过来的参数，赋值给data里的参数
      this.edit.detail = value;
    },
    // 获得表格信息
    getAllGoods() {
      this.$http
        .get(this.apiObj.goods, {
          page: this.page,
          page_size: this.page_size
        })
        .then(data => {
          if (data.status == 200) {
            this.total = data.content.goods_num;
            this.goodsInfo = data.content.goods_info;
            // console.log(this.goodsInfo)
          }
        });
    },
    // 提交商品
    submitGoods() {
      // this.$refs.upload.sendAddImgUrl();
      console.log(this.img_urls);
      this.$http
        .post(this.apiObj.goods, {
          category_id: this.category_id,
          good_name: this.add_name,
          unit: this.unit,
          details: this.details,
          img_urls: this.img_urls.join(","),
          specs: JSON.stringify(this.specList)
        })
        .then(data => {
          if (data.status == 200) {
            this.addVisible = false;
            this.getAllGoods();
            this.category_id = "";
            // this.good_name='',
            (this.unit = ""),
              (this.details = ""),
              (this.stock = ""),
              (this.price = ""),
              (this.real_price = ""),
              (this.img_urls = []),
              (this.add_name = ""),
              (this.guige = "");
            // 置空规格
            // this.specList = [];
            this.specItem = {
              name: "",
              stock: "",
              price: "",
              real_price: ""
            };
            this.$message({
              message: `${data.content.msg}`,
              type: "success"
            });
          } else {
            this.$message({
              message: `${data.content.msg}`,
              type: "error"
            });
          }
        });
    },
    // 编辑
    editInfo(value) {
      this.EditVisible = true;
      this.$store.commit("changeEditInfo", value);
      this.edit = Object.assign({},value)
      console.log(value);
      // this.edit.good_id = value.id
      this.specList = value.specs;
      this.edit.detail = value.details;
      this.edit.category_id = this.edit.category_id.toString();
      // 将要编辑的图片深拷贝一份给img_urls  再传给upload组件  是传的数组对象，引用同一个内存区域所以子组价内的数组修改会改变父组件里的img_urls
      this.img_urls = value.imgs.slice(0);
    },
    // 提交编辑
    submitEdit() {
      // console.log(this.edit.unit);
      var info = {};
      info.unit = this.edit.unit;
      info.detail = this.edit.detail;
      info.good_name = this.edit.name;
      info.img_urls = this.img_urls.join(",");
      info.category_id = this.edit.category_id;
      info.good_id = this.edit.id;
      info.specs = JSON.stringify(this.specList);
      if (
        !info.unit ||
        !info.detail ||
        !info.good_name ||
        !info.img_urls ||
        !info.category_id ||
        !info.good_id ||
        info.specs.length == 0
      ) {
        this.$message({
          message: `请完成内容`,
          type: "error"
        });
        return;
      }
      this.$http.put(this.apiObj.goods, info).then(data => {
        if (data.status == 200) {
          this.$message.success(`${data.content.msg}`);
          this.EditVisible = false;
          // 置空规格
          this.specList = [];
          this.specItem = {
            name: "",
            stock: "",
            price: "",
            real_price: ""
          };
          this.getAllGoods();
        } else {
          this.$message.error(`${data.content.msg}`);
        }
      });
    },
    // 删除商品
    deleteGoods(id) {
      this.$confirm("此操作将删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.$http
            .delete(this.apiObj.goods, {
              good_id: id
            })
            .then(res => {
              if (res.status == 200) {
                this.$message.success(`${res.content.msg}`);
                this.getAllGoods();
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleCurrentChange(page) {
      var page_num = this.coupon_num / this.page_size;
      if (this.page > Math.ceil(page_num)) {
        return false;
      }
      // console.log(Math.ceil(page_num))
      this.page = page;
      this.getAllGoods();
    }
  },
  mounted() {
    this.getAllGoods();
  }
};
</script>
<style lang="scss" scoped>
.mainImg {
  height: 100px;
}
.spec_item {
  width: 90%;
  border: 1px solid #f8f8f8;
  padding: 6px;
  span {
    color: #f56c6c;
  }
}
</style>

<style>
.editor_content {
  width: 100% !important;
  /* height: 300px; */
}
</style>


